<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'m8:orderRoute:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <a-divider orientation="left" orientation-margin="0px"
      >数铣配置【{{ picInfo.picname + '|' + picInfo.picno }}】</a-divider
    >

    <!--  -->
    <BasicForm @register="registerForm">
      <template #sxList>
        <a-button class="mb-2" @click="handleRouteDataChildAdd" v-auth="'m8:order:sx:add'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('添加工序') }}
        </a-button>
        <span class="tips">最后一个工序的截止时间必填!</span>
        <BasicTable
          @register="registerRouteDataChildTable"
          @row-click="handleRouteDataChildRowClick"
        >
          <template #sortUp="{ record }">
            <a @click="clickUp(record)" style="padding: 8px">
              <Icon icon="ant-design:arrow-up-outlined" size="18" color="#efbd47" />
            </a>
            <a @click="clickDown(record)">
              <Icon icon="ant-design:arrow-down-outlined" size="18" color="#efbd47" />
            </a>
          </template>
          <template #checkBox="{ record, column }">
            <Checkbox v-model:checked="record[column.dataIndex]"> </Checkbox>
          </template>
          <!-- <template #operCode="{ record }">
            <div v-if="!record.isNewRecord">{{ record.oper.operName }}</div>
            <div v-else>
              <a-tree-select
                v-model="code"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="Please select"
                allow-clear
                tree-default-expand-all
                @treeData="()=>operTreeData({onlyParent: 1,bsx: 0,})"
                tree-node-filter-prop="label"
              >
              </a-tree-select>
            </div>
          </template> -->
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasM8OrderRouteForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { M8SxOrderRoute, M8SxRouteSave, sxRouteForm } from '/@/api/bas/m8OrderRoute';
  import { manTreeData } from '/@/api/bas/oper';
  import { operTreeData } from '/@/api/bas/route/route';
  import { Checkbox } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register', 'closeModal', 'openDrawer']);

  const { t } = useI18n('bas.m8OrderRoute');
  const { showMessage } = useMessage();
  const record = ref<M8SxOrderRoute>({} as M8SxOrderRoute);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增数铣工艺') : t('编辑数铣工艺'),
  }));

  let picInfo = ref<any>({
    picno: '',
    picname: '',
  });

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('订单编号'),
      field: 'order.id',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      show: false,
    },
    {
      label: t('图纸编号'),
      field: 'orderPic.id',
      component: 'Input',
      defaultValue: computed(() => picInfo.value.id),
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show: false,
    },
    {
      label: t('上传文件'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => picInfo.value.id),
        bizType: 'm8OrderPic_file',
        uploadType: 'all',
        maxSize: 100,
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('负责人'),
      field: 'sxManCode',
      fieldLabel: 'sxManName',
      component: 'TreeSelect',
      componentProps: {
        api: manTreeData,
        params: { operCode: 'BC' },
        canSelectParent: false,
        allowClear: true,
      },
      //required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('投图方式'),
      field: 'isnew',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'm8_order_pic_isnew',
      },
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('工时/分'),
      field: 'jgtime',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('顺序号'),
      field: 'csort',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show: false,
    },
    {
      label: t('编程备注'),
      field: 'bcOver.remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 200,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'sxList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'sxList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });
  let canEditOper = ref<boolean>();
  let canEditQty = ref<boolean>();

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await sxRouteForm(data);
    picInfo.value = res.m8OrderPic;
    canEditOper.value = res.canEditOper;
    canEditQty.value = res.canEditQty;
    record.value = (res.m8OrderPic || {}) as M8SxOrderRoute;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setRouteDataChildTableData(res);
    setDrawerProps({ loading: false });
  });

  const [registerRouteDataChildTable, RouteDataChildTable] = useTable({
    actionColumn: {
      width: 80,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRouteDataChildDelete.bind(this, record),
          },
          auth: record.id ? 'm8:order:sx:oper:delete' : '',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: true, //是否显示序列号
  });

  async function setRouteDataChildTableData(_res: Recordable) {
    RouteDataChildTable.setColumns([
      {
        title: t('上移 / 下移'),
        slot: 'sortUp',
        width: 90,
      },
      {
        title: t('历史工序'),
        dataIndex: 'oldOper',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        ifShow: false,
      },
      {
        title: t('历史序号'),
        dataIndex: 'oldSort',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        ifShow: false,
      },
      {
        title: t('历史数量'),
        dataIndex: 'oldQty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
        ifShow: false,
      },
      {
        title: t('工序'),
        dataIndex: 'oper.operCode',
        dataLabel: 'oper.operName',
        width: 150,
        align: 'center',
        editRow: canEditOper.value,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: operTreeData,
          params: {
            onlyParent: 0,
            bsx: 1,
          },
          canSelectParent: false,
        },
        editRule: true,
        // slot: 'operCode',
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: canEditQty.value,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('加工时长'),
        dataIndex: 'jgtime',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('调试时长'),
        dataIndex: 'tstime',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('单价'),
        dataIndex: 'fprice',
        width: 80,
        align: 'center',
        defaultHidden: true,
        editRow: true,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('复杂面'),
        dataIndex: 'bhard',
        slot: 'checkBox',
        align: 'center',
        width: 80,
      },
      {
        title: t('班次数'),
        dataIndex: 'teamQty',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
      },
      {
        title: t('开始时间'),
        dataIndex: 'beginTime',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: false,
      },
      {
        title: t('截止时间'),
        dataIndex: 'endTime',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: false,
      },
      {
        title: t('加工备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
      },
    ]);
    if (record.value.sxList) {
      record.value.sxList.forEach((item, index) => {
        if (!item.id) {
          item.id = index + 1;
        }
      });
    }

    RouteDataChildTable.setTableData(record.value.sxList || []);
  }

  function handleRouteDataChildAdd() {
    RouteDataChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  // 删除新增行
  function handleRouteDataChildDelete(record: Recordable) {
    RouteDataChildTable.deleteTableDataRecord(record);
  }

  function clickUp(record) {
    // 上移
    let arr = RouteDataChildTable.getDataSource();

    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }

    if (index === 0) {
      return false;
    }

    arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    RouteDataChildTable.setTableData(arr || []);
  }

  // 下移
  function clickDown(record) {
    let arr = RouteDataChildTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === arr.length - 1) {
      return false;
    }
    arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    RouteDataChildTable.setTableData(arr || []);
  }

  //获取表格数据
  async function getRouteDataChildList() {
    let routeDataChildListValid = true;
    let routeDataChildList: Recordable[] = [];
    for (const record of RouteDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        routeDataChildListValid = false;
      }
      routeDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of RouteDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      routeDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!routeDataChildListValid) {
      throw { errorFields: [{ name: ['routeDataChildList'] }] };
    }
    return routeDataChildList;
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      console.log(data);
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.id = picInfo.value['orderPic.id']; // 图片id
      data.sxList = (await getRouteDataChildList()).map((item) => {
        item.bhard = item.bhard ? 1 : 0;
        return item;
      });
      // console.log('submit', params, data, record);
      const res = await M8SxRouteSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  function handleRouteDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  const handleChange = (info: UploadChangeParam) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  };

  // function handleChange(info: UploadChangeParam) {
  //   if (info.file.status !== 'uploading') {
  //     console.log(info.file, info.fileList);
  //   }
  //   if (info.file.status === 'done') {
  //     message.success(`${info.file.name} file uploaded successfully`);
  //   } else if (info.file.status === 'error') {
  //     message.error(`${info.file.name} file upload failed.`);
  //   }
  // }
</script>

<style scoped>
  .tips {
    padding: 10px;
    color: red;
  }
</style>
